package com.qdsgjsfk.vision.util;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by HP on 2019/3/11.
 */

public class BleBlueToothUtils {

    //申请权限
    private static final int permission_LocationCode = 101;
    //打开gps定位
    private static final int open_GPSCode = 102;

    private static String[] permissionsIndex;

    /**
     * 是否可以解析成json
     *
     * @time 2020/5/14 13:40
     */
    public static boolean getJSONType(String str) {

        str = str.trim();

        if (str.startsWith( "{" ) && str.endsWith( "}" )) {

            return true;

        } else return str.startsWith( "[" ) && str.endsWith( "]" );

    }

    /**
     * 与设备配对
     */
    static public boolean createBond(Class btClass, BluetoothDevice btDevice) throws Exception {
        Method createBondMethod = btClass.getMethod( "createBond" );
        Boolean returnValue = (Boolean) createBondMethod.invoke( btDevice );
        return returnValue.booleanValue();
    }

    /**
     * 与设备解除配对
     */
    static public boolean removeBond(Class<?> btClass, BluetoothDevice btDevice) throws Exception {
        Method removeBondMethod = btClass.getMethod( "removeBond" );
        Boolean returnValue = (Boolean) removeBondMethod.invoke( btDevice );
        assert returnValue != null;
        return returnValue.booleanValue();
    }

    /**
     * 进行配对
     */
    static public boolean setPin(Class<? extends BluetoothDevice> btClass, BluetoothDevice btDevice, String str) throws Exception {
        try {
            Method removeBondMethod = btClass.getDeclaredMethod( "setPin",
                    new Class[]
                            {byte[].class} );
            Boolean returnValue = (Boolean) removeBondMethod.invoke( btDevice,
                    new Object[]
                            {str.getBytes()} );
            Log.e( "returnValue", "" + returnValue );
        } catch (SecurityException e) {
            // throw new RuntimeException(e.getMessage());
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // throw new RuntimeException(e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 取消用户输入
     */
    static public boolean cancelPairingUserInput(Class<?> btClass, BluetoothDevice device) throws Exception {
        Method createBondMethod = btClass.getMethod( "cancelPairingUserInput" );
        Boolean returnValue = (Boolean) createBondMethod.invoke( device );
        assert returnValue != null;
        return returnValue.booleanValue();
    }

    /**
     * 取消配对
     */
    static public boolean cancelBondProcess(Class<?> btClass, BluetoothDevice device) throws Exception {
        Method createBondMethod = btClass.getMethod( "cancelBondProcess" );
        Boolean returnValue = (Boolean) createBondMethod.invoke( device );
        assert returnValue != null;
        return returnValue.booleanValue();
    }

    /**
     * 确认配对
     */
    static public void setPairingConfirmation(Class<?> btClass, BluetoothDevice device, boolean isConfirm) throws Exception {
        Method setPairingConfirmation = btClass.getDeclaredMethod( "setPairingConfirmation", boolean.class );
        setPairingConfirmation.invoke( device, isConfirm );
    }

    /**
     * 此方法用来检查gps和定位权限，先检查gps是否打开，在检查是否有定位权限
     *
     * @param activity    上下文对象
     * @param permissions 权限的名称
     */
    public static boolean checkLocalPermissiion(Activity activity, String[] permissions) {
        permissionsIndex = permissions;
        if (checkGPSIsOpen( activity )) {
            return checkPermissions( activity );
        } else {
            Toast.makeText( activity, "需要打开GPS定位", Toast.LENGTH_SHORT ).show();
            goToOpenGPS( activity );
        }
        return false;
    }

    /**
     * 检查GPS是否打开
     */
    private static boolean checkGPSIsOpen(Activity activity) {
        LocationManager locationManager = (LocationManager) activity.getSystemService( Context.LOCATION_SERVICE );
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER );
    }

    /**
     * 检查权限并申请权限
     */
    private static boolean checkPermissions(final Activity activity) {
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissionsIndex) {
            int permissionCheck = ContextCompat.checkSelfPermission( activity, permission );
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                return true;
            } else {
                permissionDeniedList.add( permission );
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray( new String[0] );
            ActivityCompat.requestPermissions( activity, deniedPermissions, permission_LocationCode );
        }
        return false;
    }

    /**
     * 去手机设置打开GPS
     */
    private static void goToOpenGPS(Activity activity) {
        Intent intent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS );
        activity.startActivityForResult( intent, open_GPSCode );

    }

}